<template>
  <div class="content">
    <!-- 顶部 -->
    <Topic :topic-info="topicInfo" @addRole="() => addRole('新增角色')" />
    <!-- 查询条件 -->
    <TableFilter :search-params.sync="tableParams" :items="searchForm" :is-show-btn-label="false">
      <!-- <template slot="suffix-button">
        <el-button type="warning" @click="addRole('新增角色')">新 增</el-button>
      </template> -->
    </TableFilter>
    <el-row :gutter="15">
      <!--角色管理-->
      <el-col :md="15" :lg="15" :xl="17">
        <!-- table组件 -->
        <SrmTable
          ref="table"
          url="get|trafficfly-manager/api/roles"
          :is-load="true"
          :hidden="true"
          :highlight="true"
          :params="tableParams"
          :columns="TableConfig"
          :table-attr="tableAttr"
          @editRole="editRole"
          @deletRole="deletRole"
          @handleCurrentChange="handleCurrentChange"
        />
      </el-col>
      <!-- 菜单授权 -->
      <el-col :md="9" :lg="9" :xl="7">
        <!-- <RoleTree /> -->
        <el-card class="box-card tree-card" shadow="never" style="position: relative;">
          <el-button type="primary" :disabled="!showButton" :loading="menuLoading" class="save" icon="el-icon-check" style="margin-left: 20px;" @click="saveMenu">保 存</el-button>
          <el-tabs v-model="tabmenuName">
            <el-tab-pane label="菜单分配" name="menu">
              <el-tree
                ref="menu"
                :data="menus"
                :default-checked-keys="menuIds"
                :props="defaultProps"
                accordion
                show-checkbox
                check-strictly
                :render-after-expand="false"
                node-key="id"
                @check-change="checkChange"
              />
            </el-tab-pane>
            <el-tab-pane label="区域配置" name="area">
              <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
              <el-tree
                ref="area"
                :data="areas"
                :default-checked-keys="areaIds"
                :props="defaultareaProps"
                accordion
                show-checkbox
                node-key="code"
                @check-change="checkareaChange"
              />
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
    <!-- 新增编辑角色 -->
    <ToRole :show-role.sync="showRole" :title="title" :edit-data="editData" @search="search" />
  </div>
</template>
<script>
import { searchForm } from './config/Search'
import { TableConfig } from './config/Table'
import { getMenusTree, getMenuSuperior, getAllMenus } from '@/api/system/menu'
import { getLevel, editMenu, get, del, getRolesAddressShow } from '@/api/system/role'
import ToRole from './components/ToRole'
import { getRolesAddress, getRolesAddressInit } from '@/api/common'
export default {
  components: { ToRole },
  data() {
    return {
      checkAll: false,
      tabmenuName: 'menu',
      topicInfo: {
        title: '角色管理',
        interactive: [
          {
            info: '新增',
            click: 'addRole'
          }
        ]
      },
      editData: {},
      menuLoading: false,
      showButton: false,
      currentId: 0,
      menus: [],
      menuIds: [],
      areas: [],
      areaIds: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      defaultareaProps: {
        children: 'children',
        label: 'fullName'
      },
      title: '新增角色',
      showRole: false,
      TableConfig: TableConfig,
      total: 100,
      searchForm: searchForm,
      tableParams: {
        blurry: ''
      },
      tableAttr: { border: true },
      level: 3,
      areaallnum: 0,
      isSetmenuChecked: false
      // checkedIds: [],
      // areafirstLevel:[],
    }
  },
  created() {
    getLevel().then(data => {
      this.level = data.level
    })
    this.getAllMenusInit()
    this.getAddressInit()
  },
  methods: {
    // 保存
    saveMenu() {
      this.menuLoading = true
      const role = { id: this.currentId, menus: [], manageCity: '' }
      const _checkedIds = [...new Set(this.$refs.menu.getCheckedKeys().concat(this.$refs.menu.getHalfCheckedKeys()))]
      const _areacheckedIds = [...new Set(this.$refs.area.getCheckedKeys().concat(this.$refs.area.getHalfCheckedKeys()))]
      role.menus = _checkedIds.map(item => {
        return {
          id: item
        }
      })
      // console.log(_checkedIds);return;
      if (_areacheckedIds.length == this.areaallnum) {
        role.manageCity = 'all'
      } else {
        _areacheckedIds.forEach((code) => {
          if (code.length == 2) {
            let str = ''
            const province = this.areas.filter(item => item.code == code)
            str = province[0].code + '-' + province[0].fullName + ':'
            _areacheckedIds.forEach((_code) => {
              if (_code.length == 4 && code == _code.slice(0, 2)) {
                const city = province[0].children.filter(item => item.code == _code)
                str += city[0].code + '-' + city[0].fullName + ','
              }
            })
            str = str.slice(0, str.length - 1)
            str += ';'
            role.manageCity += str
          }
        })
      }
      editMenu(role).then(res => {
        this.menuLoading = false
        this.$refs.table.initTable()
        // location.reload();
        // this.update()
      }).catch(err => {
        this.menuLoading = false
        console.log(err.response.data.message)
      })
    },
    // 获取所有城市
    getAddressInit() {
      getRolesAddressInit().then(res => {
        this.areas = res
        let allnum = 0
        res.forEach((item, index) => {
          allnum += item.children.length
        })
        this.areaallnum = allnum + res.length
        console.log(res, '获取所有城市')
      })
    },
    // 获取所有菜单
    getAllMenusInit() {
      getAllMenus().then(res => {
        console.log(res.list, '获取所有菜单')
        this.menus = res.list
      })
    },

    // 点击table行
    handleCurrentChange(val) {
      if (val) {
        this.getrefmenuDatas(val)
        this.getrefareaDatas(val)
      }
    },

    getrefmenuDatas(val) {
      const _this = this
      // 清空菜单的选中
      this.isSetmenuChecked = false
      this.$refs.menu.setCheckedKeys([])
      // 保存当前的角色id
      this.currentId = val.id
      this.showButton = this.level <= val.level
      // 初始化
      this.menuIds = []
      // 菜单数据需要特殊处理
      const menuIds = []
      val.menus.forEach(function(data, index) {
        menuIds.push(data.id)
        // _this.checkedIds.push(data.id)
      })
      _this.menuIds = menuIds
      setTimeout(() => {
        _this.isSetmenuChecked = true
      }, 500)

      // getMenuSuperior(this.menuIds).then(res => {
      //   this.menus = res.list
      // })
    },
    getrefareaDatas(val) {
      const _this = this
      // 清空菜单的选中
      this.checkAll = false
      this.$nextTick(() => {
        this.$refs.area.setCheckedKeys([])
      })
      _this.areaIds = []
      const areaIds = []
      getRolesAddressShow({ addressId: '0', roleId: val.id }).then(res => {
        res.forEach(function(data, index) {
          if (data.manage) {
            areaIds.push(data.code)
            if (data.children) {
              data.children.forEach(function(item, i) {
                if (item.manage) {
                  areaIds.push(item.code)
                }
              })
            }
          }
        })
        areaIds.forEach(value => {
          this.$refs.area.setChecked(value, true, false)
        })
      })
    },

    search() {
      this.$refs.table.initTable()
    },
    addRole(title) {
      this.showRole = true
      this.title = title
    },
    // 编辑
    editRole(val, title) {
      this.editData = val
      this.showRole = true
      this.title = title
    },
    // 删除角色
    deletRole(v) {
      // console.log(v)
      this.$confirm('确认要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del([v.id]).then(res => {
          this.$refs.table.initTable()
          this.$message.success('删除成功~')
        })
      }).catch(() => {})
    },
    handleCheckAllChange(val) {
      if (this.checkAll) {
        this.$refs.area.setCheckedNodes(this.areas)
      } else {
        this.$refs.area.setCheckedKeys([])
      }
    },
    checkChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate)
      const _this = this
      if (_this.isSetmenuChecked) {
        if (checked && data.children) {
          data.children.forEach(function(item, index) {
            _this.$refs.menu.setChecked(item.id, true)
          })
        }
        if (!checked && data.children) {
          data.children.forEach(function(item, index) {
            _this.$refs.menu.setChecked(item.id, false)
          })
        }
      }
    },

    checkareaChange(data, checked, indeterminate) {
      if (!checked || this.$refs.area.getCheckedKeys().length < this.areaallnum) {
        this.checkAll = false
      }
      if (this.$refs.area.getCheckedKeys().length >= this.areaallnum) {
        this.checkAll = true
      }
    }

    // getMenuDatas(node, resolve) {
    //   setTimeout(() => {
    //     getMenusTree(node.data.id ? node.data.id : 0).then(res => {
    //       resolve(res.list)
    //     })
    //   }, 100)
    // },
    // getAreaDatas(node, resolve){
    //   let _this = this;
    //   //如果有code  并且第一次加载的areafirstLevel数组里面包含这个code  说明是二级菜单，则返回空，禁止显示第三级
    //   if(node.data.code && this.areafirstLevel.indexOf(node.data.code) == -1){
    //     resolve([]);
    //     return;
    //   }
    //   setTimeout(()=>{
    //     getRolesAddress({addressId:node.data.code? node.data.code : "0"}).then(res =>{
    //       if(!node.data.code){
    //         //如果没有code  说明是第一次加载，把code push到areafirstLevel
    //         this.areafirstLevel = res.map(function(item,index){
    //           return item.code;
    //         })
    //       }
    //       //如果有currentId并且有code  说明已经选择了某个角色，把code push到areaIds 可以被选中
    //       if(this.currentId && node.data.code){
    //         res.forEach(function(data, index) {
    //           if(data.manage){
    //             _this.areaIds.push(data.code)
    //           }
    //         })
    //       }
    //       resolve(res);
    //     })
    //   },100)
    // },

  }
}
</script>
<style lang="scss" scoped>
.content{
    background-color: #fff;
    padding: 20px;
    .role-span {
      font-weight: bold;
      color: #303133;
      font-size: 15px;
    }
    .save{
      position: absolute;
      top: 20px;
      left: 70%;
      z-index: 1000;
    }
}
</style>
